package com.thirdgroup.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String resourcePath = request.getPathInfo().substring(1); // 去除路径中的前导斜杠
        System.out.println("进入图片加载servlet ---"+ resourcePath);
        if(resourcePath == null ||"".equals(resourcePath)||"undefined".equals(resourcePath)){
            System.out.println("resourcePath 为 null");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String saveDir = getServletContext().getRealPath("/") + "uploads";
        String filePath = saveDir + File.separator + resourcePath;

        File file = new File(filePath);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String contentType = getServletContext().getMimeType(filePath);
        if (contentType != null) {
            response.setContentType(contentType);
        }

        try (InputStream inputStream = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
